import ReconnectingWebSocket from 'reconnecting-websocket'
import {
  getKey
} from '../service'
export default {
  data() {
    return {
      key: ''
    }
  },
  async mounted() {
    await this.getKey();
    this.initWebSocket();
  },
  methods: {
    // 初始化websocket
    initWebSocket() {
      const options = {
        WebSocket: WebSocket, // 使用标准的 WebSocket 构造函数
        connectionTimeout: 5000, // 连接超时时间（毫秒）
        maxRetries: 3, // 最大重试次数
        debug: false // 是否开启调试模式
      };
      const rws = this.rws = new ReconnectingWebSocket(window.config.wsHost, [], options)
      rws.addEventListener('open', () => {
        // 连接打开后发送消息
        rws.send(JSON.stringify({
          msg_id: '776',
          key: this.key
        }))
      });
      rws.addEventListener('message', (event) => {
        // 收到消息的回调
        // console.log('收到消息', event.data);
        if (event.data) {
          const data = JSON.parse(event.data)
          if (data.msg_id === '778') {
            // 处理消息
            this.key_person_cnt = data.data.key_person_cnt
            this.stranger_cnt = data.data.stranger_cnt
            this.white_list_cnt = data.data.white_list_cnt
          } else if (data.msg_id === '777') { // 处理告警
            const item = data.data;
            if (this.shouldShow(item)) {
              this.showSnapList.unshift(item)
              if (this.showSnapList.length > 3) {
                this.showSnapList.pop()
              }
            } else if(item.obj_label === 1) {
              this.snapFaceList.unshift(item)
              if (this.snapFaceList.length > 8) {
                this.snapFaceList.pop()
              }
            } else if(item.obj_label === 2) {
              this.snapBodyList.unshift(item)
              if (this.snapBodyList.length > 8) {
                this.snapBodyList.pop()
              }
            } else if(item.vehicle_attr) {
              this.snapVehicleList.unshift(item)
              if (this.snapVehicleList.length > 8) {
                this.snapVehicleList.pop()
              }
            }
            this.playAudio(item)
          }
        }
      })
      // 初始化websocket
    },


    // 关闭websocket
    closeWebSocket() {
      // 关闭websocket
    },
    getKey() {
      return getKey().then(res => {
        if (res.code === 0) {
          this.key = res.data.key
        }
      })
    }
  }
}